package com.example.test.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.example.test.bean.BasicArea;
import com.example.test.bean.BasicArea2;
import com.example.test.bean.TreeNode;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class TreeUtil {

    // 将集合转为树

    public static <T extends TreeNode<T>> List<T> toTree(Collection<T> list) {

        List<T> result = CollectionUtil.newArrayList();

        Map<String, T> map = MapUtil.newHashMap();

        for (T t : list) {
            String id = t.getId();
            String parentId = t.getParentId();
            Integer depth = t.getDepth();

            if (depth == null || depth == 0 || parentId == null || !map.containsKey(parentId)) {
                result.add(t);
            } else {
                T parent = map.get(parentId);
                List<T> children = parent.getChildren();
                if (CollectionUtil.isEmpty(children)) {
                    children = CollectionUtil.newArrayList();
                }
                children.add(t);
                parent.setChildren(children);
            }
            map.put(id, t);
        }
        return result;
    }

    public static void main(String[] args) {
        List<BasicArea> result = CollectionUtil.newArrayList();
        result.add(new BasicArea("0",null,0));
        result.add(new BasicArea("1","0",1));
        result.add(new BasicArea("2","1",2));
        result.add(new BasicArea("3","2",3));
        result.add(new BasicArea("4","0",1));

        List<BasicArea2> result2 = CollectionUtil.newArrayList();
        result2.add(new BasicArea2("0",null,0));
        result2.add(new BasicArea2("1","0",1));
        result2.add(new BasicArea2("2","1",2));
        result2.add(new BasicArea2("3","2",3));
        result2.add(new BasicArea2("4","0",1));



        List<BasicArea> basicAreas = toTree(result);
        List<BasicArea2> basicAreas2 = toTree(result2);

        System.out.println(JSONUtil.toJsonStr(basicAreas));
        System.out.println(JSONUtil.toJsonStr(basicAreas2));


    }


}
